"use strict";

import React from 'react';
import PropTypes from 'prop-types';
import { StyleSheet, TouchableOpacity, TouchableHighlight, View, Image ,Dimensions ,Platform} from 'react-native';
import ListView from 'deprecated-react-native-listview'
import Color from '../../config/theme/standard/color';
import Fonts from '../../config/theme/standard/fonts'
import Label from "../label/index";

const ds = new ListView.DataSource({rowHasChanged: (r1,r2)=>(r1!==r2)});

class PopoverContainer extends React.Component {

    constructor(props) {
        super(props);
        this.state = {//设置初值
            dataSource: ds.cloneWithRows(this.props.list),
        };
    }

    static getDerivedStateFromProps(nextProps, prevState) {
        if (('list' in nextProps) && (ds.cloneWithRows(nextProps.list) !== prevState.dataSource)) {
            return {
                dataSource: ds.cloneWithRows(nextProps.list)
            };
        }
        return null;
    }

    handleClick(data) {
        console.log(data,data.text);
        this.props.onClick(data.text, data);
        this.props.onClose();
    }

    renderRow(rowData) {
        const separatorStyle =  [styles.separator];
        const rowContainerStyle = [styles.rowContainer];
        const rowStyle = [styles.row];

		if(!this.props.fullSeparator){
			separatorStyle.push({marginLeft:12,width:116});
		}

		separatorStyle.push({backgroundColor: this.props.separatorColor});

        const { hasIcon } = this.props;

        let separator = <View style={separatorStyle}/>;
        if (rowData === this.props.list[0]) {
            separator = null;
            rowStyle.push({borderTopLeftRadius: 5, borderTopRightRadius: 5});
        } else if (rowData === this.props.list[this.props.list.length-1]) {
            rowStyle.push({borderBottomLeftRadius: 5, borderBottomRightRadius: 5});
        }

        let row;
        let textColor = this.props.type == 'black' ? 'white' : Color.popover.text;
        if (hasIcon) {
            row = (
                <View style={[rowContainerStyle, {justifyContent: 'flex-start'}]}>
                    <Image style={styles.image} source={rowData.icon}/>
                    <Label text={rowData.text}  labelStyle={{paddingLeft: 4,fontSize:Fonts.popover.textFontSize, color:textColor,fontWeight:'400' }} numberOfLines={1}/>
                </View>
            )

        } else {
            let textAlign = null;
            if(this.props.textAlign === 'left'){
                textAlign = {justifyContent: 'flex-start'};
                rowContainerStyle.push({paddingLeft:12});
            }else if(this.props.textAlign === 'right'){
                textAlign = {justifyContent: 'flex-end'};
                rowContainerStyle.push({paddingRight:12});
            }else{
                textAlign = {justifyContent: 'center'};
            }
            row = (
                <View style={[rowContainerStyle,textAlign]}>
                    <Label text={rowData.text} labelStyle={{fontSize:Fonts.popover.textLargeFontSize,
                    color:textColor, fontWeight:'400'}} numberOfLines={1}/>
                </View>
            )
        }

        return (
            <View 
            accessible={true}
            accessibilityRole={'button'}
            >
                {separator}
                <TouchableHighlight
                    style={rowStyle}
                    activeOpacity={this.props.type == 'black' ? 0.8 : 1}
                    underlayColor={this.props.type == 'black' ? 'transparent' : Color.button.disable}
                    onPress={() => this.handleClick(rowData)}
                >
                    {row}
                </TouchableHighlight>
            </View>
        );
    }

    renderList() {
        const styles = this.props.style || styles;
        let maxHeight = {};
        if (this.props.list.length > 12) {
            maxHeight = {height: Dimensions.get('window').height * 3/4}
        }
        return (
            <ListView
                style={maxHeight}
                dataSource={this.state.dataSource}
                renderRow={(rowData) => this.renderRow(rowData)}
            />
        );
    }

    render() {

        const containerStyle =  [styles.container];
        const popoverStyle =  [styles.popover];
        const popoverContainer = [styles.popoverContainer];
        const triangleStyle = [styles.triangle];
        const triangleIconStyle = [styles.triangleIcon];
        let borderColor = this.props.type == 'black' ? Color.popover.backgroundBlack : Color.white;

        switch (this.props.direction) {
            case ('rightUp'):
                triangleStyle.push({
                    borderTopColor: Color.transparent,
                    borderRightColor: Color.transparent,
                    borderBottomColor: borderColor,
                    borderLeftColor: Color.transparent,
                });
                triangleIconStyle.push({
                    borderTopColor: Color.transparent,
                    borderRightColor: Color.transparent,
                    borderBottomColor: borderColor,
                    borderLeftColor: Color.transparent,
                    opacity: 0.8,
                });
                break;
            case ('leftUp'):
                triangleStyle.push({
                    left: 18,
                    borderTopColor: Color.transparent,
                    borderRightColor: Color.transparent,
                    borderBottomColor: borderColor,
                    borderLeftColor: Color.transparent,
                });
                triangleIconStyle.push({
                    left: 18,
                    borderTopColor: Color.transparent,
                    borderRightColor: Color.transparent,
                    borderBottomColor: borderColor,
                    borderLeftColor: Color.transparent,
                });
                break;
            case ('left'):
                triangleStyle.push({
                    borderTopWidth: 16 / 2.0,
                    borderRightWidth: 9,
                    borderBottomWidth: 16 / 2.0,
                    borderLeftWidth: 0,
                    borderTopColor: Color.transparent,
                    borderRightColor: borderColor,
                    borderBottomColor: Color.transparent,
                    borderLeftColor: Color.transparent,
                    position: 'relative',
                    left: -10,
                    top: 28,
                });
                triangleIconStyle.push({
                    borderTopWidth: 16 / 2.0,
                    borderRightWidth: 9,
                    borderBottomWidth: 16 / 2.0,
                    borderLeftWidth: 0,
                    borderTopColor: Color.transparent,
                    borderRightColor: borderColor,
                    borderBottomColor: Color.transparent,
                    borderLeftColor: Color.transparent,
                    position: 'relative',
                    left: -10,
                    top: 28,
                });
                break;
            case ('right'):
                triangleStyle.push({
                    borderTopWidth: 16/2.0,
                    borderRightWidth: 0,
                    borderBottomWidth: 16/2.0,
                    borderLeftWidth: 9,
                    borderTopColor: Color.transparent,
                    borderRightColor: Color.transparent,
                    borderBottomColor: Color.transparent,
                    borderLeftColor: borderColor,
                    position: 'relative',
                    left: 140,
                    top: 28,
                });
                triangleIconStyle.push({
                    borderTopWidth: 16/2.0,
                    borderRightWidth: 0,
                    borderBottomWidth: 16/2.0,
                    borderLeftWidth: 9,
                    borderTopColor: Color.transparent,
                    borderRightColor: Color.transparent,
                    borderBottomColor: Color.transparent,
                    borderLeftColor: borderColor,
                    position: 'relative',
                    left: 140,
                    top: 28,
                });
                break;
        }

        if(this.props.type == 'black'){
            containerStyle.push({backgroundColor: 'rgba(0,0,0,0)'});
            popoverStyle.push({backgroundColor: Color.popover.backgroundBlack});
        }

        if (this.props.isVisible) {
            return (
                <TouchableOpacity onPress={this.props.onClose} style={containerStyle} accessible={false}>
                    <View style={[popoverContainer, this.props.position]}>
                        <View style={this.props.hasIcon ? triangleIconStyle : triangleStyle}/>
                        <View style={this.props.hasIcon ? [popoverStyle, {width: 140}] : popoverStyle}>
                            {this.renderList()}
                        </View>
                    </View>
                </TouchableOpacity>
            );
        } else {
            return (<View/>);
        }
    }
}

PopoverContainer.propTypes = {
    list: PropTypes.array.isRequired,
    isVisible: PropTypes.bool,
    onClick: PropTypes.func,
    onClose: PropTypes.func,
    popoverStyle: PropTypes.any,
    hasIcon: PropTypes.bool,
    //是否气泡样式一（是/否）
    direction: PropTypes.oneOf (['rightUp','leftUp','left','right']),
    //箭头方向（右上/左上/左/右）
    type:PropTypes.oneOf(['black','white']),
    //类型
	fullSeparator: PropTypes.bool,
	separatorColor: PropTypes.string,
    textAlign:PropTypes.oneOf (['left','center','right']),
};

PopoverContainer.defaultProps = {
    list: [""],
    isVisible: false,
    onClick: () => {},
    onClose: () => {},
    hasIcon: false,
    position: [],
    direction: 'rightUp',
    type:'white',
	fullSeparator: false,
    separatorColor:Color.popover.separator,
    textAlign:'center'
};

const styles = StyleSheet.create({
    container: {
        position: 'absolute',
        width: '100%',
        height: '100%',
        zIndex: 10,
        backgroundColor: 'rgba(0,0,0,0.4)',
    },

    popoverContainer: {
        position: 'absolute',
        width: 140,
        right: 5,
        top: 55,
        zIndex: 1
    },

    popover: {
        backgroundColor: Color.popover.background,
        borderRadius: 4,
        width: 140,
    },

    //复选样式二的箭头样式
    triangle: {
        width: 16,
        height: 9,
        backgroundColor: 'transparent',
        borderStyle: 'solid',
        borderTopWidth: 0,
        borderRightWidth: 16/2, //width/2
        borderBottomWidth: 9,   //height
        borderLeftWidth: 16/2,  //width/2
        borderTopColor: 'transparent',
        borderRightColor: 'transparent',
        borderBottomColor: Color.white,
        borderLeftColor: 'transparent',
        position: 'relative',
        left: 114,
    },

    //复选样式一的箭头样式
    triangleIcon: {
        width: 16,
        height: 9,
        backgroundColor: 'transparent',
        borderStyle: 'solid',
        borderTopWidth: 0,
        borderRightWidth: 16/2, //width/2
        borderBottomWidth: 9,   //height
        borderLeftWidth: 16/2,  //width/2
        borderTopColor: 'transparent',
        borderRightColor: 'transparent',
        borderBottomColor: Color.white,
        borderLeftColor: 'transparent',
        position: 'relative',
        left: 112,
    },

    rowContainer: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        width: 140,
        height: 44
    },

    separator: {
        height: 1
    },

    image: {
        width: 28,
        height: 28,
        marginLeft: 12,
        resizeMode:'contain'
    }
});

module.exports = PopoverContainer;
